package com.yyx.server.config.component;

import com.yyx.server.pojo.Menu;
import com.yyx.server.pojo.Role;
import com.yyx.server.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 根据请求的URL分析请求所需的角色
 * @author YongXin
 * @date Created in 2021/7/29 18:00
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private MenuService menuService;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取请求的URL
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menus = menuService.getMenusWithRole();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (Menu menu : menus) {
            //判断请求URL与菜单角色是否匹配
            if (antPathMatcher.match(menu.getUrl(),requestUrl)){
                List<Role> roles = menu.getRoles();
                String[] strings=new String[roles.size()];
                for (int i=0;i<roles.size();i++){
                    strings[i]=roles.get(i).getName();
                }
                return SecurityConfig.createList(strings);
            }
        }
        //没匹配的URL默认登录
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
